<template>
  <div class="face-recognition">
    <h2>监控中心</h2>
    <div class="video-container">
      <div class="video-controls">
        <el-button type="primary" @click="pauseVideo" class="pause-video-button">暂停</el-button>
        <el-button type="primary" @click="playVideo" class="play-video-button">播放</el-button>
        <el-button type="primary" @click="replayVideo" class="replay-video-button">重新播放</el-button>
        <el-slider v-model="currentFrame" :max="totalFrames" @change="setVideoPosition" show-tooltip></el-slider>
      </div>
      <img ref="video" :src="currentImage" alt="video stream"/>
    </div>
    <div class="control-panel">
      <el-form :model="form" label-width="120px">
        <el-form-item label="模型类型">
          <el-radio-group v-model="modelType">
            <el-radio label="目标追踪">目标追踪</el-radio>
            <el-radio label="吸烟检测">吸烟检测</el-radio>
            <el-radio label="烟雾明火检测">烟雾明火检测</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="模型再分类">
          <el-radio-group v-model="modelSize">
            <el-radio label="n">n</el-radio>
            <el-radio label="s">s</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-button type="primary" @click="changeModel" class="change-model-button">更改模型</el-button>
        <el-button type="primary" @click="startRecognition" class="start-recognition-button">开始目标识别</el-button>
        <el-button type="primary" @click="startVideoStream" class="start-video-button">获取实时视频</el-button>
        <el-form-item label="上传视频" class="upload-video-item">
          <el-upload
            class="upload-demo"
            action="http://localhost:5001/upload_video"
            :on-success="handleUploadSuccess"
            :file-list="fileList"
          >
            <el-button slot="trigger" type="primary">选取视频</el-button>
            <div slot="tip" class="el-upload__tip">上传本地视频进行处理</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="设置区域">
          <div class="coordinates">
            <span>x1:</span>
            <el-input v-model="regionX1" placeholder="左上角 x 坐标" style="width: 80px;"></el-input>
            <span>y1:</span>
            <el-input v-model="regionY1" placeholder="左上角 y 坐标" style="width: 80px;"></el-input>
            <span>x2:</span>
            <el-input v-model="regionX2" placeholder="右下角 x 坐标" style="width: 80px;"></el-input>
            <span>y2:</span>
            <el-input v-model="regionY2" placeholder="右下角 y 坐标" style="width: 80px;"></el-input>
            <el-button type="primary" @click="setRegion" style="margin-left: 10px;">设置区域</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div v-if="processedFrames.length">
        <h3>处理后的视频帧：</h3>
        <div class="processed-frames">
          <img v-for="(frame, index) in processedFrames" :key="index" :src="frame" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FaceRecognition',
  data() {
    return {
      video: null,            // 视频元素引用
      form: {},               // 表单数据对象
      modelType: '目标追踪',   // 模型类型
      modelSize: 'n',         // 模型大小
      fileList: [],           // 上传文件列表
      processedFrames: [],    // 处理后的视频帧
      uploadedVideoUrl: '',   // 上传的视频URL
      isUploadedVideo: false, // 标识是否上传了视频
      regionX1: 100,
      regionY1: 100,
      regionX2: 400,
      regionY2: 400,
    };
  },
  mounted() {
    this.video = this.$refs.video;
    if (this.video) {
      this.startVideoStream();  // 开始视频流
    }
  },
  methods: {
    startVideoStream() {
      const streamUrl = 'http://localhost:5000/video_feed/1';  // 获取实时视频流

      if (this.video) {
        this.updateVideoStream(this.video, streamUrl);
      }
    },

    updateVideoStream(videoElement, streamUrl) {
      // 定时刷新图片以显示视频流
      setInterval(() => {
        if (videoElement) {
          videoElement.src = streamUrl + '?timestamp=' + new Date().getTime();
        }
      }, 1000);  // 每秒刷新一次
    },
    handleUploadSuccess() {
      this.uploadedVideoUrl = `http://localhost:5000/video_feed/1`;  // 从 VIDEO_FEED_URL 获取处理后的视频流
      this.isUploadedVideo = true;
      this.$nextTick(() => {
        const uploadedVideoElement = this.$refs.uploadedVideo;
        if (uploadedVideoElement) {
          this.updateVideoStream(uploadedVideoElement, this.uploadedVideoUrl);
        }
      });
    },
    changeModel() {
      // 调用后端API更改模型
      fetch('http://localhost:5001/change_model', {  // 更改为不同的端点
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model_type: this.modelType,
          model_size: this.modelSize,
        }),
      }).then(response => {
        if (response.ok) {
          console.log('模型更改成功');
        } else {
          console.error('模型更改失败');
        }
      });
    },
    startRecognition() {
      fetch('http://localhost:5001/start_recognition', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      }).then(response => {
        if (response.ok) {
          console.log('目标识别已启动');
          this.startVideoStream();  // 开始获取视频流
        } else {
          console.error('启动目标识别失败');
        }
      }).catch(error => {
        console.error('Fetch error:', error);
      });
    },
    pauseVideo() {
      this.isPlaying = false;
      fetch('http://localhost:5001/pause_video', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      }).then(response => {
        if (response.ok) {
          console.log('视频已暂停');
        } else {
          console.error('暂停视频失败');
        }
      }).catch(error => {
        console.error('Fetch error:', error);
      });
    },
    playVideo() {
      this.isPlaying = true;
      fetch('http://localhost:5001/play_video', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      }).then(response => {
        if (response.ok) {
          console.log('视频已播放');
        } else {
          console.error('播放视频失败');
        }
      }).catch(error => {
        console.error('Fetch error:', error);
      });
    },
    replayVideo() {
      this.currentFrame = 0;
      this.isPlaying = true;
      fetch('http://localhost:5001/replay_video', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      }).then(response => {
        if (response.ok) {
          console.log('视频已重新播放');
        } else {
          console.error('重新播放视频失败');
        }
      }).catch(error => {
        console.error('Fetch error:', error);
      });
    },
    setVideoPosition() {
      const data = {
        frame_position: this.currentFrame
      };
      fetch('http://localhost:5001/set_video_position', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
      }).then(response => {
        if (response.ok) {
          console.log('视频位置已设置');
        } else {
          console.error('设置视频位置失败');
        }
      }).catch(error => {
        console.error('Fetch error:', error);
      });
    }, setRegion() {
      const regionData = {
        x1: this.regionX1,
        y1: this.regionY1,
        x2: this.regionX2,
        y2: this.regionY2
      };
      fetch('http://localhost:5001/set_region', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(regionData)
      }).then(response => {
        if (response.ok) {
          console.log('Region updated');
        } else {
          console.error('Failed to update region');
        }
      }).catch(error => {
        console.error('Fetch error:', error);
      });
    },
    calculateDistanceFromDangerArea(position, dangerArea) { // eslint-disable-line no-unused-vars
      // 计算人员位置与危险区域边缘的距离，实际应用中需具体实现
      return 0; // 示例值，实际需具体计算
    },
    triggerAlarm() {
      console.log('触发告警');
      // 实现告警逻辑，例如发送告警信息等
    },
  }
};
</script>

<style scoped>
.face-recognition {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.video-container {
  width: 100%;
  max-width: 800px; /* 视频容器最大宽度 */
  position: relative;
}

.video-controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
  display: flex;
  flex-direction: row;
  gap: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 10px;
  border-radius: 5px;
}

img {
  width: 100%;
  height: auto;
  object-fit: cover;
}

.control-panel {
  margin-top: 20px;
  width: 100%;
  max-width: 800px; /* 控制面板最大宽度 */
}

.processed-frames {
  display: flex;
  flex-wrap: wrap;
}

.processed-frames img {
  margin: 5px;
  max-width: 200px;
}

.change-model-button {
  margin-bottom: 20px;
}

.start-recognition-button {
  margin-bottom: 20px;
}

.start-video-button {
  margin-bottom: 20px;
}

.upload-video-item {
  margin-top: 15px;
}
</style>
